package com.cema.manage.project.android.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cema.manage.common.exception.BizException;
import com.cema.manage.mail.MailService;
import com.cema.manage.project.android.model.PageVo;
import com.cema.manage.project.android.model.result.BizRewardRecord;
import com.cema.manage.project.android.service.BizRewardRecordService;
import com.cema.manage.project.android.service.BizUserService;
import com.cema.manage.project.enums.RedisEnum;
import com.cema.manage.project.manage.adRecord.domain.AdRecord;
import com.cema.manage.project.manage.adRecord.domain.AdRecordVo;
import com.cema.manage.project.manage.adRecord.service.IAdRecordService;
import com.cema.manage.project.manage.antiCheat.service.IAntiCheatService;
import com.cema.manage.project.manage.rewardRecord.domain.RewardRecord;
import com.cema.manage.project.manage.rewardRecord.mapper.RewardRecordMapper;
import com.cema.manage.project.manage.rewardRecord.service.IRewardRecordService;
import com.cema.manage.project.manage.users.domain.Users;
import com.cema.manage.project.util.DateUtils;
import com.cema.manage.redis.RedisService;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 奖励记录 服务层实现
 *
 * @author reasahi
 * @date 2024-07-08
 */
@Service
public class BizRewardRecordServiceImpl implements BizRewardRecordService {
    @Resource
    private BizUserService bizUserService;
    @Resource
    private IRewardRecordService rewardRecordService;
    @Resource
    private RewardRecordMapper rewardRecordMapper;
    @Resource
    private IAdRecordService iAdRecordService;
    @Resource
    private IAntiCheatService iAntiCheatService;

    @Resource
    private RedisService redisService;

    @Resource
    private MailService mailService;

    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public boolean signIn(Users users, Integer money, String realityMoney,String uvChannel) {
        lock.lock();
        try {
            EntityWrapper<RewardRecord> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("rr_source_type", 1);
            DateUtils.getCurrentDayTime(entityWrapper, "create_time");
            entityWrapper.eq("us_id", users.getId());
            RewardRecord rewardRecord = rewardRecordService.selectOne(entityWrapper);
            if (ObjectUtil.isNotNull(rewardRecord)) {
                return false;
            }
            String signNumber = (String) redisService.get(RedisEnum.WITHDRAWAL_NUMBER_SIGN.getKey()+uvChannel);
            EntityWrapper<AdRecord> adRecordEntityWrapper = new EntityWrapper<>();
            adRecordEntityWrapper.eq("us_id", users.getId());
            DateUtils.getCurrentDayTime(adRecordEntityWrapper, "create_time");
            int count = iAdRecordService.selectCount(adRecordEntityWrapper);
            if (count < Integer.parseInt(signNumber)) {
                throw new BizException("每天答题" + signNumber + "次,可获得红包奖励,还差" + (Integer.parseInt(signNumber) - count) + "次");
            }
            if (count < Integer.parseInt(signNumber)) {
                //发送邮件
                String name = (String) redisService.get(RedisEnum.APP_NAME.getKey());
                mailService.sendSimpleMail("异常通知", name + "【用户ID：" + users.getId() +
                        "】【用户名：" + users.getNickname() + "】【今日任务进度：" + count + "】");
            }
            rewardRecord = new RewardRecord();
            rewardRecord.setUsId(users.getId());
            rewardRecord.setRrMoney(money);
            rewardRecord.setUsNickname(users.getNickname());
            rewardRecord.setRrSourceType(1);
            rewardRecord.setRrType(2);
            rewardRecordService.insert(rewardRecord);
            Users userUpdate = new Users();
            userUpdate.setSignIdDayNumber(users.getSignIdDayNumber() + 1);
            userUpdate.setSignInNumber(users.getSignInNumber() + 1);
            userUpdate.setMoneyRedPacket(users.getMoneyRedPacket() + money);
            userUpdate.setSignIn(1);
            userUpdate.setId(users.getId());
            //更新用户缓存
            users.setSignInNumber(users.getSignInNumber() + 1);
            users.setSignIdDayNumber(users.getSignIdDayNumber() + 1);
            users.setMoneyRedPacket(users.getMoneyRedPacket() + money);
            users.setSignIn(1);
            redisService.set(users.getOpenid() + users.getDeviceId(), users);
            return bizUserService.updateById(userUpdate);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public List<RewardRecord> getRewardRecord(Integer uid, PageVo pageVo) {
        String current = pageVo.getCurrent();
        String size = pageVo.getSize();
        int sizeC = Integer.parseInt(size);
        int pageSize = (Integer.parseInt(current) - 1) * sizeC;
        RowBounds rowBounds = new RowBounds(pageSize, sizeC);
        EntityWrapper<RewardRecord> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("us_id", uid);
        entityWrapper.eq("rr_type", pageVo.getQueryValue());
        //自己的归属
        entityWrapper.orderBy("create_time", false);
        return rewardRecordMapper.selectPage(rowBounds, entityWrapper);
    }

    @Override
    public BizRewardRecord getRewardRecordByTransId(Users users, String transId) {
        EntityWrapper<RewardRecord> rewardRecordEntityWrapper = new EntityWrapper<>();
        rewardRecordEntityWrapper.eq("rr_trans_id", transId);
        List<RewardRecord> rewardRecordList = rewardRecordService.selectList(rewardRecordEntityWrapper);
        if (ObjectUtil.isNull(rewardRecordList) || rewardRecordList.size() == 0) {
            return null;
        }
        BizRewardRecord bizRewardRecord = new BizRewardRecord();
        for (RewardRecord rewardRecord : rewardRecordList) {
            if (rewardRecord.getRrType() == 1) {
                bizRewardRecord.setValueJingBi(rewardRecord.getRrMoney().toString());
            } else {
                bizRewardRecord.setValueHongBao(rewardRecord.getRrMoney().toString());
            }
        }
        bizRewardRecord.setRiskAdvertisingCoins(iAntiCheatService.checkRiskAdvertisingCoins(users.getId()));
        bizRewardRecord.setRiskAdvertisingCoinsThanEqual(iAntiCheatService.checkRiskAdvertisingCoinsThanEqual(users.getId()));
        bizRewardRecord.setRiskAdvertisingCoinsThanEqualTwo(iAntiCheatService.checkRiskAdvertisingCoinsThanEqualTwo(users.getId()));
        bizRewardRecord.setRiskWhiteList(iAntiCheatService.checkRiskWhiteList(users.getId()));
        return bizRewardRecord;
    }

    @Override
    public void createAdRecord(Users users, AdRecordVo adRecordVo) {
        //平台默认1：1000000
        Double ecpm = adRecordVo.getEcpm();
        //修改比例1：10000
        ecpm = ecpm / 10;
        //分配给用户
        String allocationAd = (String) redisService.get(RedisEnum.ALLOCATION_AD.getKey() + adRecordVo.getUvChannel());
        Integer kik = StrUtil.isNotEmpty(allocationAd) ? Integer.parseInt(allocationAd) : 0;
        if (ObjectUtil.isNotNull(users.getKickback())) {
            kik = users.getKickback();
        }
        double kickback = kik / 100.0;
        ecpm = ecpm * kickback;
        //创建广告激励
        AdRecord adRecord = new AdRecord();
        adRecord.setUsNickname(users.getNickname());
        adRecord.setUsId(users.getId());
        adRecord.setUsMoney(ecpm.intValue());
        adRecord.setUsKickback(kik);
        adRecord.setArRealityMoney((int) (adRecordVo.getEcpm() / 10.0));
        adRecord.setArChannel("ad_" + adRecordVo.getArChannel());
        adRecord.setArMediationRit(adRecordVo.getArMediationRit());
        adRecord.setArTransId(adRecordVo.getArTransId());
        adRecord.setUvChannel(adRecordVo.getUvChannel());
        //默认有广告位
        adRecord.setArPrimeRit(redisService.get(RedisEnum.TA_KU_INCENTIVE_VIDEO_CALLBACK.getKey()+adRecordVo.getUvChannel()).toString());
        iAdRecordService.insert(adRecord);
    }
}
